package com.business_clean.ui.fragment.main;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseFragment;
import com.business_clean.app.callback.OnDialogTimePickerListener;
import com.business_clean.app.config.Constant;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.app.weight.EqualSpacingItemDecoration;
import com.business_clean.app.weight.dialog.CameraSettingDialog;
import com.business_clean.app.weight.dialog.CustomClockInDialog;
import com.business_clean.app.weight.dialog.CustomTimePickerPopup;
import com.business_clean.app.weight.dialog.PagerDrawerPopup;
import com.business_clean.data.initconfig.MenuEntity;
import com.business_clean.data.mode.attendance.AttendanceEntity;
import com.business_clean.data.mode.project.ProjectManager;
import com.business_clean.data.mode.project.ProjectMangerList;
import com.business_clean.data.mode.workbench.HomeEntity;
import com.business_clean.data.mode.workbench.WorkBenchEntity;
import com.business_clean.databinding.FragmentStagingBinding;
import com.business_clean.databinding.HeaderHomeBinding;
import com.business_clean.databinding.HeaderHomeFooterBinding;
import com.business_clean.ui.activity.attendance.ProjectAttendanceActivity;
import com.business_clean.ui.activity.custom.AddProjectActivity;
import com.business_clean.ui.activity.personnel.SelectPersonnelActivity;
import com.business_clean.ui.adapter.BaseMenuAdapter;
import com.business_clean.ui.adapter.home.HomeCardAdapter;
import com.business_clean.viewmodel.request.HomeVideModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.luck.picture.lib.decoration.MyGridSpacingItemDecoration;
import com.lxj.xpopup.XPopup;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * 这里是工作台
 */
public class WorkbenchFragment extends BaseFragment<HomeVideModel, FragmentStagingBinding> {

    private HomeCardAdapter mAdapter;

    private HeaderHomeBinding headerHomeBinding;
    private HeaderHomeFooterBinding headerHomeFooterBinding;

    private BaseMenuAdapter menuAdapter;

    private boolean isToDay = true;//记录是日考勤还是月考勤


    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        mAdapter = new HomeCardAdapter();
        getMDatabind().list.recyclerView.setAdapter(mAdapter);
        getMDatabind().list.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        getMDatabind().list.recyclerView.addItemDecoration(new EqualSpacingItemDecoration(SizeUtils.dp2px(10)));
        getMDatabind().list.recyclerView.setBackgroundResource(R.color.base_primary_bg_page);

        //列表头
        View headerView = requireActivity().getLayoutInflater().inflate(R.layout.header_home, null);
        headerHomeBinding = DataBindingUtil.bind(headerView);
        mAdapter.setHeaderView(headerView);
        //列表尾部
//        View footerView = requireActivity().getLayoutInflater().inflate(R.layout.header_home_footer, null);
//        headerHomeFooterBinding = DataBindingUtil.bind(footerView);
//        mAdapter.setFooterView(footerView);

        //设置底部企业信息
//        if (App.appViewModelInstance.getUserInfo().getValue() != null) {
//            headerHomeFooterBinding.tvCompanyName.setText(App.appViewModelInstance.getUserInfo().getValue().getCompany().getCompany_name());
//            headerHomeFooterBinding.tvCompanyNameAll.setText(App.appViewModelInstance.getUserInfo().getValue().getCompany().getFull_name());
//            headerHomeFooterBinding.ivCompany.setAvatar("", App.appViewModelInstance.getUserInfo().getValue().getCompany().getCompany_name());
//            headerHomeFooterBinding.ivCompany.getAvatarText().setTextSize(16f);
//        }

        LogUtils.e("当前项目的 uuid " + App.appViewModelInstance.getProjectInfo().getValue().getUuid());


        //统计需要显示的内容
        menuAdapter = new BaseMenuAdapter();
        headerHomeBinding.recyclerAttendance.setAdapter(menuAdapter);
        headerHomeBinding.recyclerAttendance.setLayoutManager(new GridLayoutManager(getActivity(), 5));
        headerHomeBinding.recyclerAttendance.addItemDecoration(new MyGridSpacingItemDecoration(5, SizeUtils.dp2px(10), false));


        getAttendanceStat(null);

        headerHomeBinding.tvHomeChangeDate.setText(TimeUtils.millis2String(TimeUtils.getNowMills(), "yyyy-MM-dd"));
        headerHomeBinding.tvHomeChangeDateMonth.setText(TimeUtils.millis2String(TimeUtils.getNowMills(), "yyyy-MM"));

        getMDatabind().list.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                request(false);
                getMDatabind().list.refreshLayout.finishRefresh(1000);
            }
        });
        getMDatabind().list.refreshLayout.setEnableLoadMore(false);

        request(false);


        // 处理管理员和人事角色是否显示切换按钮
        handleRoleVisibility(Constant.ROLE_ID, getMDatabind().tvHomeChange, "1", "3");

        // 处理首页的Home标签显示内容根据身份
        handleRoleVisibility(Constant.ROLE_ID, headerHomeBinding.llStatisticsAll, "1", "2", "3", "4");

        // 处理首页的用工统计权限判断
        handleRoleVisibility(Constant.ROLE_ID, headerHomeBinding.llStatisticsWork, "1", "2", "3");
    }


    // 封装权限处理逻辑的方法
    private void handleRoleVisibility(String roleId, View view, String... allowedRoles) {
        boolean show = Arrays.asList(allowedRoles).contains(roleId);
        if (show) {
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.GONE);
        }
    }


    private void request(boolean hideDialog) {
        mViewModel.requestWorkbenchStat(hideDialog);
        mViewModel.requestWorkbenchGrid(hideDialog);
        if (Constant.ROLE_MANGER || Constant.ROLE_HR) {
            mViewModel.requestProjectAllList(hideDialog);
        }
    }

    @Override
    public void initObserver() {
        //监听选择项目
        App.appViewModelInstance.getProjectInfo().observe(this, new Observer<ProjectMangerList>() {
            @Override
            public void onChanged(ProjectMangerList projectMangerList) {
                fillTopData();
                request(true);
            }
        });

        fillTopData();

        //这里是底部grid
        getMViewModel().getHomeEntity().observe(this, new Observer<HomeEntity>() {
            @Override
            public void onChanged(HomeEntity homeEntity) {
                mAdapter.setList(homeEntity.getList());
            }
        });
        //顶部统计
        getMViewModel().getWorkBenchEntity().observe(this, new Observer<WorkBenchEntity>() {
            @Override
            public void onChanged(WorkBenchEntity workBenchEntity) {
                switchStat(true);
            }
        });
    }


    @Override
    public void onBindViewClick() {
        menuAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("position", position);
                bundle.putBoolean("isDay", isToDay);
                bundle.putString("date", headerHomeBinding.tvHomeChangeDate.getText().toString());
                bundle.putString("date_month", headerHomeBinding.tvHomeChangeDateMonth.getText().toString());
                ActivityForwardUtil.startActivity(ProjectAttendanceActivity.class, bundle);
            }
        });

        headerHomeBinding.llHeaderDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchStat(true);
            }
        });

        headerHomeBinding.llHeaderMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchStat(false);
            }
        });

        //弹出侧边栏
        getMDatabind().llChangeProject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constant.ROLE_MANGER || Constant.ROLE_HR) {
                    new XPopup.Builder(getContext())
                            .asCustom(new PagerDrawerPopup(getMActivity())).show();
//                    new XPopup.Builder(getContext())
//                            .asCustom(new CameraSettingDialog(getMActivity(), new CameraSettingDialog.CameraSettingDialogListener() {
//                                @Override
//                                public void clickChange(int how) {
//
//                                }
//                            })).show();
                }
            }
        });

        //快速入职
        headerHomeBinding.tvHomeQuickEntry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityForwardUtil.startActivity(AddProjectActivity.class);
            }
        });
        //快速离职
        headerHomeBinding.tvHomeQuickDepart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putInt("is_head_office", 2);//不要总部员工
                bundle.putBoolean("row_visible", true);
                bundle.putString("tab_title", "选择待离职人员");
                ActivityForwardUtil.startActivity(SelectPersonnelActivity.class, bundle);
            }
        });

        //人员调动
        headerHomeBinding.tvHomePersonnelTransfer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        //项目考勤
        headerHomeBinding.llStatisticsAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ActivityForwardUtil.startActivity(ProjectAttendanceActivity.class);
            }
        });

        //切换日期
        headerHomeBinding.tvHomeChangeDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar defInstance = Calendar.getInstance();

                defInstance.setTime(TimeUtils.string2Date(headerHomeBinding.tvHomeChangeDate.getText().toString(), "yyyy-MM-dd"));

                CommonUtils.showDialogTimePickerView(getMActivity(), "请选择日期", defInstance, Calendar.getInstance().get(Calendar.YEAR) - 1, Calendar.getInstance().get(Calendar.YEAR) + 1, null, null, CustomTimePickerPopup.Mode.YMD, new OnDialogTimePickerListener() {
                    public void onTimeChanged(Date date) {
                    }

                    @Override
                    public void onTimeConfirm(Date date, View view) {
                        headerHomeBinding.tvHomeChangeDate.setText(TimeUtils.date2String(date, "yyyy-MM-dd"));
                        switchStat(true);
                    }
                });
            }
        });

        headerHomeBinding.tvHomeChangeDateMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar defInstance = Calendar.getInstance();
                defInstance.setTime(TimeUtils.string2Date(headerHomeBinding.tvHomeChangeDateMonth.getText().toString(), "yyyy-MM"));

                CommonUtils.showDialogTimePickerView(getMActivity(), "请选择日期", defInstance, Calendar.getInstance().get(Calendar.YEAR) - 1, Calendar.getInstance().get(Calendar.YEAR) + 1, null, null, CustomTimePickerPopup.Mode.YM, new OnDialogTimePickerListener() {
                    public void onTimeChanged(Date date) {
                    }

                    @Override
                    public void onTimeConfirm(Date date, View view) {
                        headerHomeBinding.tvHomeChangeDateMonth.setText(TimeUtils.date2String(date, "yyyy-MM"));
                        switchStat(false);
                    }
                });
            }
        });
    }


    private void fillTopData() {
        if (App.appViewModelInstance.getProjectInfo().getValue() != null) {
            ProjectMangerList mangerList = App.appViewModelInstance.getProjectInfo().getValue();
            getMDatabind().llChangeProject.setVisibility(View.VISIBLE);
            getMDatabind().tvHomeProjectName.setText(mangerList.getProject_short_name());
        }
    }


    /**
     * true 是day false 是月
     */
    private void switchStat(boolean isDay) {
        isToDay = isDay;
        headerHomeBinding.viewHeaderDay.setVisibility(isDay ? View.VISIBLE : View.GONE);
        headerHomeBinding.viewHeaderMonth.setVisibility(isDay ? View.GONE : View.VISIBLE);
        headerHomeBinding.tvHomeChangeDate.setVisibility(isDay ? View.VISIBLE : View.GONE);
        headerHomeBinding.tvHomeChangeDateMonth.setVisibility(isDay ? View.GONE : View.VISIBLE);

        mViewModel.requestAttendanceStat(isDay, App.appViewModelInstance.getProjectInfo().getValue().getUuid(),
                (isDay ? headerHomeBinding.tvHomeChangeDate.getText().toString() : headerHomeBinding.tvHomeChangeDateMonth.getText().toString()),
                "", "0");
    }


    @Override
    public void onRequestSuccess() {
        //全部的项目
        mViewModel.getAllProjectManager().observe(this, new Observer<ProjectManager>() {
            @Override
            public void onChanged(ProjectManager projectManager) {
                App.appViewModelInstance.getAllProjectManager().setValue(projectManager);
                MMKVHelper.putString(ConstantMMVK.ALL_PROJECT_LIST, JSON.toJSONString(projectManager));
            }
        });
        //统计
        mViewModel.getWorkBenchEntity().observe(this, new Observer<WorkBenchEntity>() {
            @Override
            public void onChanged(WorkBenchEntity workBenchEntity) {
                if (workBenchEntity.getWorker_statistics() != null) {
                    headerHomeBinding.tvProjectWorkInfo.setText("*立项" + workBenchEntity.getWorker_statistics().getContract_human_num() + "人，定岗" + workBenchEntity.getWorker_statistics().getTotal_job_num() + "人");
                }
            }
        });
        //工作台
        mViewModel.getHomeEntity().observe(this, new Observer<HomeEntity>() {
            @Override
            public void onChanged(HomeEntity homeEntity) {
                mAdapter.setList(homeEntity.getList());
            }
        });
        //统计
        mViewModel.getAttendanceEntity().observe(this, new Observer<AttendanceEntity>() {
            @Override
            public void onChanged(AttendanceEntity attendanceEntity) {
                getAttendanceStat(attendanceEntity);
            }
        });
    }

    private void getAttendanceStat(AttendanceEntity data) {
        List<MenuEntity> attenDances = new ArrayList<>();
        if (data != null) {
            attenDances.add(new MenuEntity("" + data.getAll_total(), "人", "在岗", "#000000"));
            if (!isToDay) {//如果是月报g
                attenDances.add(new MenuEntity("" + data.getEntry_total(), "人", "入职", "#000000"));
                attenDances.add(new MenuEntity("" + data.getLeft_total(), "人", "离职", "#000000"));
            }
            attenDances.add(new MenuEntity("" + data.getRest_total(), "人", "休息", "#000000"));
            attenDances.add(new MenuEntity("" + data.getShould_attendance_total(), "人", "应出勤", "#000000"));
            attenDances.add(new MenuEntity("" + data.getActual_attendance_total(), "人", "实出勤", "#09BE89"));
            attenDances.add(new MenuEntity("" + data.getHoliday_total(), "人", "休假", "#A671CF"));
            attenDances.add(new MenuEntity("" + data.getOvertime_total(), "人", "加班", "#1890FF"));
            attenDances.add(new MenuEntity("" + data.getAbsenteeism_total(), "人", "旷工", "#FF4040"));
            attenDances.add(new MenuEntity("" + data.getQk_total(), "人", "缺卡", "#FF801A"));
        } else {
            attenDances.add(new MenuEntity("0", "人", "在岗", "#000000"));
            attenDances.add(new MenuEntity("0", "人", "休息", "#000000"));
            attenDances.add(new MenuEntity("0", "人", "应出勤", "#000000"));
            attenDances.add(new MenuEntity("0", "人", "实出勤", "#09BE89"));
            attenDances.add(new MenuEntity("0", "人", "休假", "#A671CF"));
            attenDances.add(new MenuEntity("0", "人", "加班", "#1890FF"));
            attenDances.add(new MenuEntity("0", "人", "旷工", "#FF4040"));
            attenDances.add(new MenuEntity("0", "人", "缺卡", "#FF801A"));
        }
        menuAdapter.setList(attenDances);
    }


}
